// 引入样式
require("./zjf-sport-video.less");
// 引入字体图标
require("../../libs/download/font_mf1p4fskz4/iconfont.js");
require("../../libs/download/font_mf1p4fskz4/iconfont.css");
// 引入axios
let axios = require("axios");

document.addEventListener("DOMContentLoaded", function () {
	axios.defaults.baseURL = "http://fitness.h5.itsource.cn:3701";
	let token = localStorage.getItem("token");
	axios.defaults.headers.common["Authorization"] = "Bearer " + token;
	// 获取方法
	function $(v) {
		return document.querySelector(v);
	}
	let data = JSON.parse(localStorage.getItem("data")).fragments;
	// 声明一个变量用来控制当前结数
	let n = 0;
	//总共的时间
	let duration = 0;
	// 开始的时间戳
	let start = Date.now();
	function play() {
		$("#video").src = axios.defaults.baseURL + data[n].videoUrl;
		$("#length").textContent = data.length;
		$("#title").textContent = data[n].title;
		$("#now").textContent = n + 1;
		// 播放进度条
		setInterval(function () {
			$("#nowtime").style.width =
				(video.currentTime * 100) / video.duration + "%";
		}, 20);
	}
	play();
	// 播放完自动进入下一页
	$("#video").addEventListener("ended", function () {
		n++;
		if (n === data.length) {
			// alert("训练结束");
			//训练结束
			duration = Math.ceil(duration / 1000);
			let calorie = Math.ceil(duration * 1.57);
			axios
				.post("/api/exercise/save", {
					type: 2,
					duration,
					calorie,
				})
				.then((v) => {
					alert("本次训练结束");
					location.href = "zjf-sport-introduce.html";
				});
		}
		play();
	});
	// 上一节
	$("#left").addEventListener("click", function () {
		if (n === 0) {
			n = data.length - 1;
			console.log(n);
		} else {
			n--;
		}
		play();
	});
	// 下一节
	$("#right").addEventListener("click", function () {
		n++;
		if (n === data.length) {
			n = 0;
		}
		play();
	});

	// 暂停
	$("#play").addEventListener("click", function () {
		$("#mask").style.display = "block";
		$("#box").style.display = "block";
		$("#video").pause();
		duration += Date.now() - start;
		console.log(duration);
	});
	// 点击取消蒙层
	$("#continue").addEventListener("click", function () {
		$("#mask").style.display = "none";
		$("#box").style.display = "none";
		video.play();
		start = Date.now();
	});
	$("#mask").addEventListener("click", function () {
		$("#mask").style.display = "none";
		$("#box").style.display = "none";
		$("#video").play();
		start = Date.now();
	});

	// 结束训练
	$("#outText").addEventListener("click", function () {
		duration = Math.ceil(duration / 1000);
		let calorie = Math.ceil(duration * 1.57);
		axios
			.post("/api/exercise/save", {
				type: 2,
				duration,
				calorie,
			})
			.then((v) => {
				alert("本次训练结束");
				location.href = "zjf-sport-introduce.html";
			});
	});
});
